const https = require('https')
const http = require('http')

const API_BASE_URL = 'http://localhost:5000/api'

// 通用API请求函数
async function apiRequest(endpoint, options = {}) {
  const url = `${API_BASE_URL}${endpoint}`
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  return new Promise((resolve, reject) => {
    const urlObj = new URL(url)
    const isHttps = urlObj.protocol === 'https:'
    const client = isHttps ? https : http
    
    const requestOptions = {
      hostname: urlObj.hostname,
      port: urlObj.port || (isHttps ? 443 : 80),
      path: urlObj.pathname + urlObj.search,
      method: defaultOptions.method || 'GET',
      headers: defaultOptions.headers
    }

    if (defaultOptions.body) {
      requestOptions.headers['Content-Length'] = Buffer.byteLength(defaultOptions.body)
    }

    const req = client.request(requestOptions, (res) => {
      let data = ''
      
      res.on('data', (chunk) => {
        data += chunk
      })
      
      res.on('end', () => {
        try {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            const jsonData = JSON.parse(data)
            resolve(jsonData)
          } else {
            reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`))
          }
        } catch (error) {
          reject(new Error(`JSON解析失败: ${error.message}`))
        }
      })
    })

    req.on('error', (error) => {
      reject(new Error(`请求失败: ${error.message}`))
    })

    if (defaultOptions.body) {
      req.write(defaultOptions.body)
    }
    
    req.end()
  })
}

// 测试创建任务
async function testCreateTask() {
  console.log('🧪 测试创建任务...')
  
  const taskData = {
    title: '测试任务 - 明天下午3点开会',
    description: '这是一个测试任务',
    dueDate: '2024-12-20',
    priority: 'P1',
    category: 'work',
    tags: ['测试', '会议'],
    notes: '测试备注'
  }
  
  try {
    console.log('📝 发送任务数据:', taskData)
    
    const result = await apiRequest('/tasks', {
      method: 'POST',
      body: JSON.stringify(taskData)
    })
    
    console.log('✅ 任务创建成功!')
    console.log('📊 返回结果:', result)
    
    if (result.id) {
      console.log('🆔 任务ID:', result.id)
      console.log('💬 消息:', result.message)
    }
    
  } catch (error) {
    console.error('❌ 任务创建失败:', error.message)
  }
}

// 测试获取所有任务
async function testGetAllTasks() {
  console.log('\n📋 测试获取所有任务...')
  
  try {
    const tasks = await apiRequest('/tasks', {
      method: 'GET'
    })
    
    console.log('✅ 获取任务成功!')
    console.log(`📊 共找到 ${tasks.length} 个任务:`)
    
    tasks.forEach((task, index) => {
      console.log(`  ${index + 1}. ${task.title} (${task.category}) - ${task.priority}`)
    })
    
  } catch (error) {
    console.error('❌ 获取任务失败:', error.message)
  }
}

// 主测试函数
async function runTests() {
  console.log('🚀 开始测试任务创建功能...\n')
  
  await testCreateTask()
  await testGetAllTasks()
  
  console.log('\n🎉 测试完成!')
}

// 运行测试
if (require.main === module) {
  runTests().catch(error => {
    console.error('❌ 测试执行失败:', error.message)
    process.exit(1)
  })
}

module.exports = {
  testCreateTask,
  testGetAllTasks
}
